<template>
  <el-dialog v-model="dialogVisible" :destroy-on-close="true" width="450px" :title="`${dialogProps.title}字典配置`">
    <el-form
        ref="ruleFormRef"
        label-width="100px"
        label-suffix=" :"
        :rules="rules"
        :disabled="dialogProps.isView"
        :model="dialogProps.rowData"
        :hide-required-asterisk="dialogProps.isView"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="dialogProps.rowData.name" placeholder="配置名称" clearable />
      </el-form-item>
      <el-form-item label="编码" prop="code">
        <el-input v-model="dialogProps.rowData.code" placeholder="配置编码" clearable />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="dialogProps.rowData.status">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" v-show="!dialogProps.isView" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";

interface DialogProps {
  title: string;
  isView: boolean;
  rowData?: any;
  api?: (params: any) => Promise<any>;
  getTreeData?: () => Promise<any>;
  updateTreeData?: () => Promise<any>;
}

const rules = reactive({
  name: [{ required: true, message: "请填写字典配置名称" }],
  code: [{ required: true, message: "请填写字典配置编码" }],
  status: [{ required: true, message: "请选择字典配置状态" }]
});

// drawer框状态
const dialogVisible = ref(false);
const dialogProps = ref<DialogProps>({
  isView: false,
  title: ""
});

// 接收父组件传过来的参数
const acceptParams = (params: DialogProps): void => {
  dialogProps.value = params;
  dialogVisible.value = true;
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await dialogProps.value.api!(dialogProps.value.rowData);
      ElMessage.success({ message: `${dialogProps.value.title}字典配置成功！` });
      if (dialogProps.value.getTreeData) {
        await dialogProps.value.getTreeData();
      }
      if (dialogProps.value.updateTreeData) {
        await dialogProps.value.updateTreeData();
      }
      dialogVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
